import { VTranRecordInfo } from '../../types/vTranRecordInfo'
import { select } from '../../utils/db'
import { Page, PageReq } from '../../types/page'
import { DoctorDao } from './doctorDao'
import { Trainer } from '../../types/trainer'
import { Course } from '../../types/course'

export class VTranRecordInfoDao {
  /**
   * 根据ID获取训练记录详情
   */
  static async getById(id: number): Promise<VTranRecordInfo> {
    const result = await select<VTranRecordInfo>(
      'SELECT * FROM v_tran_record WHERE id = ? LIMIT 1',
      [id]
    )
    return result[0]
  }

  /**
   * 今日已训练患者总数
   */
  static async getTodayTrainerTotal(course_date: string): Promise<number> {
    const result = await select<VTranRecordInfo>(
      'SELECT COUNT(trainer_id) as total FROM v_tran_record WHERE course_date = ?',
      [course_date]
    )
    return result[0].total || 0
  }

  /**
   * 分页查询训练记录列表
   */
  static async page(params: PageReq<Partial<VTranRecordInfo>>): Promise<Page<VTranRecordInfo>> {
    const { pageNum, pageSize } = params
    const offset = (pageNum - 1) * pageSize
    const fields = []
    const values = []
    const queryParams = params.params
    //console.log("queryParams",queryParams)
    if (queryParams.course_id) {
      fields.push('course_id = ?')
      values.push(queryParams.course_id)
    }
   // if (queryParams.course_date) {
   //   fields.push('course_date = ?')
   //   values.push(queryParams.course_date)
   // }
    if (queryParams.train_doctor_id) {
      fields.push('train_doctor = ?')
      values.push(queryParams.train_doctor_id)
    }
    
    if (queryParams.course_time_id) {
      fields.push('course_time_id = ?')
      values.push(queryParams.course_time_id)
    }
    if (queryParams.course_time_name) {
      fields.push('course_time_name LIKE ?')
      values.push(`%${queryParams.course_time_name}%`)
    }
    if (queryParams.trainer_name) {
      fields.push('trainer_name LIKE ?')
      values.push(`%${queryParams.trainer_name}%`)
    }
    if (queryParams.scens_id) {
      fields.push('scense_id = ?')
      values.push(queryParams.scens_id)
    }
    if (queryParams.scens_name) {
      fields.push('scens_name LIKE ?')
      values.push(`%${queryParams.scens_name}%`)
    }
    if (queryParams.start_date) {
      fields.push('course_date >= ?')
      values.push(queryParams.start_date)
    }
    if (queryParams.end_date) {
      fields.push('course_date <= ?')
      values.push(queryParams.end_date)
    }

    const condition = fields.length > 0 ? `WHERE ${fields.join(' AND ')}` : ''
    const [totalResult, listResult] = await Promise.all([
      select('SELECT COUNT(*) as count FROM v_tran_record ' + condition, values),
      select(`SELECT * FROM v_tran_record ${condition} LIMIT ${pageSize} OFFSET ${offset}`, values)
    ])
    if(listResult){
      for(let item of listResult as VTranRecordInfo[]){
        if(item.train_doctor){
          const doctor =  await DoctorDao.getById(item.train_doctor)  
          if(doctor){
           item.train_doctor_name = doctor.name
          }
        }
      }
    }
    //console.log(listResult)
    return {
      total: totalResult[0].count || 0,
      list: (listResult as VTranRecordInfo[]) || []
    }
  }


  //查下已训练患者
  static async getTrainers(): Promise<Trainer[]> {
    const sql = 'SELECT DISTINCT trainer_id, trainer_name FROM  v_tran_record';
    const trainRecord = await select<VTranRecordInfo[]>(sql);
    return trainRecord.map(item => ({
      id: item.trainer_id,
      name: item.trainer_name
    })) as Trainer[]
  }

  //根据trainer_id查下训练日期
  static async getTrainerDates(trainer_id: number): Promise<Course[]> {
    const sql = 'SELECT DISTINCT course_date FROM  v_tran_record WHERE trainer_id = ?';
    const trainRecord = await select<VTranRecordInfo[]>(sql, [trainer_id]);
    return trainRecord.map(item => ({
      id: item.course_id,
      date: item.course_date
    })) as Course[]
  }

  //根据trainer_id和course_date查下训练记录
  static async getTrainerRecords(trainer_id: number, course_date: string[]): Promise<VTranRecordInfo[]> {
    if (course_date.length === 0) {
      return [];
    }
    
    // 构建IN子句的占位符和参数
    const placeholders = course_date.map(() => '?').join(',');
    const sql = `SELECT * FROM v_tran_record WHERE trainer_id = ? AND course_date IN (${placeholders})`;
    const params = [trainer_id, ...course_date];
    
    const trainRecord = await select<VTranRecordInfo[]>(sql, params);
    return trainRecord
  }
}